﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TeamFoundation.ContinuousMerge.BranchGraph
{
    /// <summary>
    /// Represents a <see cref="BranchPackage"/> the builds to a 
    /// <see cref="BranchGraph"/>.
    /// </summary>
    public class DefaultBranchPackage<TNode> : BranchPackage<BranchGraph<TNode>, TNode>
        where TNode : BranchNode, new()
    {
    }

    /// <summary>
    /// Represents a branch package.
    /// </summary>
    public class BranchPackage<TGraph, TNode> : Dictionary<string, List<string>>
        where TGraph : BranchGraph<TNode>, new()
        where TNode : BranchNode, new()
    {
        /// <summary>
        /// Build a <see cref="BranchGraph"/> from the package.
        /// </summary>
        /// <returns>The Branch Graph.</returns>
        public TGraph BuildGraph()
        {
            TGraph graph = new TGraph();
            Dictionary<string, TNode> nodes = new Dictionary<string, TNode>();

            TNode curNode;
            nodes.Add("$/", curNode = new TNode() { ServerItem = "$/" }); // Root
            graph.AddVertex(curNode);

            // Add all the vertices.
            foreach (var list in Values)
            {
                foreach (var value in list)
                {
                    nodes.Add(value, curNode = new TNode() { ServerItem = value });
                    graph.AddVertex(curNode);
                }
            }

            // All all the edges.
            foreach (var kvp in this)
            {
                curNode = nodes[kvp.Key];
                foreach (var dest in kvp.Value)
                {
                    graph.AddEdge(new QuickGraph.Edge<TNode>(curNode, nodes[dest]));
                }
            }

            return graph;
        }
    }
}
